package com.giw.uima;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.uima.TokenAnnotation;
import org.apache.uima.UimaContext;
import org.apache.uima.analysis_component.JCasAnnotator_ImplBase;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.Type;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.util.Level;

public class CoachAnnotator extends JCasAnnotator_ImplBase {

	private static final String PATH_DIZIONARIO = "dictionaryCoachpath";
	private static final String POS_FEATURENAME = "posTag";

	private List<String> namesList;

	public void initialize(UimaContext aContext)
			throws ResourceInitializationException {
		super.initialize(aContext);
		try {

			// hmm.initialize(aContext);
			namesList = IOUtils
					.readLines(new FileInputStream(String.valueOf(aContext
							.getConfigParameterValue(PATH_DIZIONARIO))));
			Collections.sort(namesList); // sort collection to make binary
											// search possible
		} catch (IOException e) {
			e.printStackTrace();
			aContext.getLogger().log(Level.SEVERE,
					"error reading dictionary file");
			throw new ResourceInitializationException(e);
		}
	}

	@Override
	public void process(JCas jcas) throws AnalysisEngineProcessException {
		// TODO Auto-generated method stub
		for (Annotation annName : jcas
				.getAnnotationIndex(PersonNameAnnotation.type)) {

			for (Annotation annToken : jcas
					.getAnnotationIndex(TokenAnnotation.type)) {

				if (annToken.getBegin() >= annName.getEnd()
						&& !annToken.getCoveredText().isEmpty()) {
					if ((isValore(annToken, "vb") || isValore(annToken, "vbn"))
							&& Collections.binarySearch(namesList,
									annToken.getCoveredText()) >= 0) {

						/*
						 * Controllo che il Token sia un verbo e che il verbo
						 * appartenga all'elenco dei verbi che mecciano con i
						 * coach. Se meccia il verbo allora posso creare
						 * CoachAnnotatiton
						 */

						
						  CoachAnnotation coachannotation = new CoachAnnotation(jcas);
						  coachannotation.setBegin(annName.getBegin());
						  coachannotation.setEnd(annName.getEnd());
						  coachannotation.addToIndexes();
						 

						/*
						 * v. 2 Devo controllare se ci sono parole che mecciano
						 * con il mio dizionario se mecciano controllo se nelle
						 * vicinanze ( massimo 2 token avanti e indietro trovo
						 * il coach.
						 */
					}

					break;

				}
			}
		}
	}

	private boolean isValore(Annotation annotation, String valore) {
		Type type = annotation.getType();
		String pos = annotation.getFeatureValueAsString(type
				.getFeatureByBaseName(POS_FEATURENAME));

		return pos != null && pos.equals(valore);
	}

}